// pages/details/details.js
import { Detail } from '../../utils/url.js';
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 1000,
      num:1,
      color:'',
      selected:'',
      selectedcolor:'',
      selectedindex:"",
      selectedsize:'',
      goodDetails:[],
      goodsName:'',
      swiperPic:'',
      discPrice:'',
      imgBig:'',
      _id:'',
      total:'',
      //购物车
      cart_null:true,
      carts:[],
      address:'未填写',
      telNumber:'未填写',
      userName:'未填写',
      detailInfo:'',
      message:'',
    //   选择图片
      uploadImgBig:'',
      chooseSrc:'../../images/upload.png',
      choosebtn:'上传设计图(图片小于800K)',
  },
//   选择图片
chooseImg:function(){
    let that = this;
    wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
            console.log(res)
            let tempFilePaths = res.tempFilePaths[0],
                lunboImg = [];
            // 判断图片大小是否超过800K
            if (res.tempFiles[0].size <= 819200){
                for(let i = 0; i<3; i++){
                    lunboImg[i]= tempFilePaths
                }
                wx.uploadFile({
                    url: Detail.uploadPic, 
                    filePath: tempFilePaths,
                    name: 'file',
                    success: function (res) {
                        that.setData({
                            choosebtn: '清除并重新上传设计图',
                            uploadImgBig: 'imgBig',
                            chooseSrc: '../../images/ok.png',
                            swiperPic: [JSON.parse(res.data).result]
                        })
                    }
                })      
            }else{
                wx.showModal({
                    title: '提示',
                    content: '图片大小超过限制！',
                })
            }            
        },
        fail: function (res) { },
        complete: function (res) { },
    });
        
},
//   跳转至购物车页面
  tocart: function (e) {
      wx.navigateTo({
          url: '../cart/cart',
      })
  },
//   再去逛逛
  backtoindex: function (e) {
      wx.showModal({
          title: '温馨提示',
          content: '离开当前页面，购物袋将会被清空哦',
          success: function (res) {
              if (res.confirm) {
                  wx.switchTab({
                      url: '../index/index',
                  })
              } else if (res.cancel) {
                  console.log('用户点击取消')
              }
          }
      })
  },

  //选择配送地址
  chooseAddress:function(){
      let that = this;
      wx.chooseAddress({
          success: function (res) {
              console.log(res)
              let address = res.provinceName+res.cityName+res.countyName;
              let detailInfo = res.detailInfo;
              let userName = res.userName;
              let telNumber = res.telNumber;
               
              that.setData({
                  address: address,
                  userName: userName,
                  telNumber: telNumber,
                  detailInfo: detailInfo,
              })
              try {
                  wx.setStorageSync('address', address);
                  wx.setStorageSync('userName', userName);
                  wx.setStorageSync('telNumber', telNumber);
                  wx.setStorageSync('detailInfo', detailInfo);
              } catch (e) {
              }
          }
      })
  },
  //   减数量
  countdown: function (e) {
      var index = e.currentTarget.dataset.index,
          carts = this.data.carts,
          num = carts[index].num;
      if (num > 1) {
          num = num - 1
      } else {
          num = 1
      };
      carts[index].num = num;
      this.setData({
          carts: carts
      });
      this.getTotalPrice()//重新计算价格
      this.getTotalNum()//重新计算总数
  },
  addcount: function (e) {
      var index = e.currentTarget.dataset.index,
          carts = this.data.carts,
          num = carts[index].num;
      num = num + 1;
      carts[index].num = num;
      this.setData({
          carts: carts
      });
      this.getTotalPrice()
      this.getTotalNum()
  },
  //   删除购物车
  deleteOnecart: function (e) {
      console.log(e)
      let carts = this.data.carts,
          cart_null = this.data.cart_null,
          index = e.currentTarget.dataset.index,
          that = this;
      wx.showModal({
          title: '亲爱的客官',
          content: '您确定要删除该商品吗？',
          success: function (res) {
              if (res.confirm) {
                      carts.splice(index, 1);
                      that.getTotalPrice();
                      that.getTotalNum();
                      if (that.getTotalNum() > 0){
                          that.setData({
                              carts: carts
                          })
                      }else{
                          that.setData({
                              cart_null: true
                          })
                      }  
              } else if (res.cancel) {
                  console.log('用户点击取消')
              }
          }
      })
  },
//   买家留言
  messageset:function(e){
        this.setData({
            message: e.detail.value
        })
  },
//   立即下单
    buynow:function(){
        let address = this.data.address,
            userName = this.data.userName,
            telNumber = this.data.telNumber,
            detailInfo = this.data.detailInfo,
            totalPrice = this.data.totalPrice,
            goodsName = this.data.goodsName,
            message = this.data.message,
            _id = this.data._id,
            swiperPic = this.data.swiperPic[0],
            discPrice = this.data.discPrice,
            carts = this.data.carts;
            console.log(carts)
        if (address == '未填写' || userName == '未填写' || telNumber == '未填写'){
            wx.showModal({
                title: '温馨提示',
                content: '请将配送信息填写完整',
            })
        }else{
            wx.login({
                success: function (res) {
                    wx.request({
                        url: Detail.update,
                        method: 'POST',
                        data: {
                            code:res.code,
                            name: userName,
                            phone: telNumber,
                            preAddress: address,
                            detailAddress: detailInfo,
                            goodsName: goodsName,
                            message: message,
                            goodsId: _id,
                            swiperPic: swiperPic,
                            discPrice: discPrice,
                            totalMoney: totalPrice,
                            payorder: carts,
                        },
                        header: {
                            'Accept': 'application/json'
                        },
                        success: function (res) {
                            // console.log(res)
                            // wx.requestPayment({
                            //     'timeStamp': res.data.result.opts.timeStamp,
                            //     'nonceStr': res.data.result.opts.nonce_str,
                            //     'package': res.data.result.opts.prepay_id,
                            //     'signType': res.data.result.opts.signType,
                            //     'paySign': res.data.result.opts.paySign,
                            //     'success': function (res) {
                            //         console.log('支付成功啦！')
                            //     },
                            //     'fail': function (res) {
                            //         console.log('支付失败啦！')
                            //     },
                            //     'complete': function (res) {
                                    wx.switchTab({
                                        url: '../my/my',
                                        success:function(e){
                                            var page = getCurrentPages().pop();
                                            if(page == undefined || page == null)
                                            return;
                                            page.onLoad();
                                        }
                                    })
                            //     }
                            // })
                        }
                    })
                }
            });

            
        }

    },


//   加入购物袋
    addcart:function(e){
        var that  = this,
            it_size = that.data.selectedsize,
            it_color = that.data.selectedcolor;
        if (it_size == '' && it_color == ''){
            wx.showModal({
                title: '亲爱的客官',
                showCancel:false,
                content: '请选择颜色和尺码哦~',
            })
        }else if (it_size == ''){
            wx.showModal({
                title: '亲爱的客官',
                showCancel: false,
                content: '您忘记选择尺码了哦~',
            })
        } else if (it_color == ''){
            wx.showModal({
                title: '亲爱的客官',
                showCancel: false,
                content: '您忘记选择颜色了哦~',
            })
        }else{
            let carts = that.data.carts;
            let obj = new Object();
            let havesame = false;
            let index = 0;
            obj.color = it_color;
            obj.size = it_size ;
            obj.num = 1;
            //数组循环 判断是否有相同的商品
            for (let i = 0; i < carts.length; i++) {
                console.log(obj.color == carts[i].color && obj.size == carts[i].size)
                if (obj.color == carts[i].color && obj.size == carts[i].size ) {
                    havesame = true;
                    index = i;
                }
            }
            if (havesame){
                carts[index].num++;//有，Number+
            }else{
                carts.push(obj);//无 添加新商品
                carts.reverse();//数组倒置
            }            
            that.setData({
                carts:carts,
                imgBig: 'imgBig',
                cart_null: false,
                selectedcolor: '',
                selectedsize: '',
            })
            that.getTotalPrice();
            that.getTotalNum();
            setTimeout(function () {
                that.setData({
                    imgBig: '',
                })
            }, 200)
            }
    },
    //   计算价格
    getTotalPrice() {
        let carts = this.data.carts;
        let discPrice = this.data.discPrice;
        let totalPrice = 0;
        for (let i = 0; i < carts.length; i++) {
                totalPrice += discPrice * carts[i].num //计算选中的总价
        }
        this.setData({
            totalPrice: totalPrice,
        })
    },
    //计算总数
    getTotalNum() {
        let carts = this.data.carts;
        let total = 0;
        for (let i = 0; i < carts.length; i++) {
             total += carts[i].num //计算选中的总数量   
        }
        this.setData({
            total: total
        })
        return total;
    },
    selectColor:function(e){
        console.log(new Date());
        console.log(e.currentTarget);
       // selectedcolor: e.currentTarget.dataset.text, 
        this.setData({
            selectedcolor: e.currentTarget.dataset.text,
        })
    },
    selectSize: function (e) {
       // selectedsize: e.currentTarget.dataset.text, 
        this.setData({
            selectedsize: e.currentTarget.dataset.text,
            selectedindex: e.currentTarget.dataset.index,
        })
        console.log(e)
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var _id = options.id;
    that.setData({
        _id: _id,
    })
    console.log(_id)
      // 商品详情页
      wx.request({
          url: Detail.onegoods,
          method: 'get',
          data: {
              _id: _id,
          },
          header: {
              'Accept': 'application/json'
          },
          success: function (res) {
              let data = res.data.result.list[0]
              that.setData({
                color: data.norms,
                discPrice: data.salePrice,//促销价
                goodsName: data.goodName,
                label: data.lable, 
                price: data.costPrice,
                salse: data.salse,
                size: data.choosesize,
                swiperPic: data.goodsfiles,
                img: data.mainfiles,
              })
              console.log(res)
          }
      })
      try {
          var add = wx.getStorageSync('address'),
              name = wx.getStorageSync('userName'),
              num = wx.getStorageSync('telNumber'),
          detailInfo = wx.getStorageSync('detailInfo');
          if (add) {
              that.setData({
                  address: add,
                  userName: name,
                  telNumber: num,
                  detailInfo: detailInfo,
              })
          }
      } catch (e) {
      }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this
    console.log(that.data.goodsName)
    if (res.form === 'button') {
      //来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: that.data.goodsName,
      path: '/pages/details/details?id='+ that.data._id,
      //imageUrl: 'http://oum84thym.bkt.clouddn.com/association.png',
      success: function (res) {
        //转发成功
        console.log('转发成功');
      },
      fail: function (res) {
        //转发失败
        console.log('转发失败');
      }
    }
  }
})